package org.lightpersist.hibernate;

import net.jcip.annotations.ThreadSafe;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
 * 
 * @author GL
 *
 */
@ThreadSafe
@Singleton
public class ThreadLocalSessionProvider extends SessionProvider{

	private final SessionFactory sessionFactory;
	private final ThreadLocal<Session> localSession;

	@Inject
	public ThreadLocalSessionProvider(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.localSession = new ThreadLocal<Session>();
	}
	
	public Session get() {
		Session s = localSession.get();
		if ((s == null) || !s.isOpen()) {
			synchronized (this) {
				if ((s == null) || !s.isOpen()){
					s = sessionFactory.openSession();
					localSession.set(s);
				}
			}
		}
		return s;
	}
	
	public void releaseSession() {
		final Session s = localSession.get();
		localSession.remove();

		if (s != null) {
			if (s.isOpen()) {
				s.flush();
				s.close();
			}
		}
	}
	
}
